import Global from "./Global";
import Utils from "./Utils";
import WxApi from "./WxApi";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {


    // onLoad () {}

    start () {

        let width = 100;
		let height = 40;

		let style = {
            left: window.innerWidth / 2 - width / 2,
			top: window.innerHeight - height * 1.5,
			width,
            height,
            lineHeight: 40,
            backgroundColor: '#ff0000',
            color: '#ffffff',
            textAlign: 'center',
            fontSize: 16,
            borderRadius: 4
		};


        if (cc.sys.platform !== cc.sys.WECHAT_GAME) {
            Global.openId = Date.now() + "_" + Math.floor(Math.random() * 1000);
			return this.handleUserInfo({nickName: "Tom", avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/EyTQicQLWjAHprpIt8UzvzXv7gp0zdf9e1ibKXriceJIkMJeZ2TByRrXF9FhXF1ibyl7aCvsv5giaPKe75PSkSBYgzg/132"});
        }
        
        //调用云函数取得 openid
        WxApi.initCloud("star-demo-rtbhb");
    
        WxApi.callFunction("getOpenid").then((res:any) =>{
            Global.openId = res.result.openid;
            cc.log(`云函数返回openid:${Global.openId}`)
        }).catch(err => {
            console.log("getOpenid invoke err", err);
            Global.openId = Date.now() + "_" + Math.floor(Math.random() * 1000);
        });

        /**
         * 获取用户信息，如果获取失败，则去授权，成功则会直接得到用户信息
         * 用户若已授权，则会走success
         * 
         */
		wx.getUserInfo({
			fail: () => {
				let button = wx.createUserInfoButton({
                     type: "text", 
                     style: style, 
                     text: "授权" });

				button.onTap( (data:any) => {
                    if(!data.userInfo){
                        return; 
                    }
					this.handleUserInfo(data.userInfo);
					button.destroy();
				});
			},
			success: data => {
				this.handleUserInfo(data.userInfo);
			}
		});
    }

    // 把用户信息存到全局对象里
    handleUserInfo(userInfo: any){
        if(!userInfo){
            return;
        }
        Global.userInfo = userInfo;
        cc.director.loadScene("home_scene");
        return;
    }
    
    // update (dt) {}
}
